#include "cmodel.h"
#include <iostream>
#include "cmachine.h"
#include "cevent.h"
#include "cmachine.h"

CModel::CModel()
{
	currentTime=0.0;
}

CModel::~CModel()
{
}

CElement* CModel::getElementByID(long id)
{
	CElement* p=(CElement*)NULL;
	CElement* p2=(CElement*)NULL;
	std::vector<CElement*>::iterator it=ElementList.begin();
	for(;it!=ElementList.end();it++)
	{
		p2=(*it);
		if(p2->getID()==id)
		{
			p=p2;
			break;
		}
	}
	return p;
}

double CModel::getCurrentTime()
{
	//
//	std::cout<<"CModel::getCurrentTime() not implemented."<<std::endl;
	return currentTime;
}

void CModel::CollectEvent(CEvent* evt)
{
	EventList.push_back(evt);
}

void CModel::Run()
{
	GenerateStartEvent();
	Forward();
}

void CModel::GenerateStartEvent()
{
	CEvent* start=new CEvent(-1,-1,0.0);
	CollectEvent(start);
	
}

void CModel::Forward()
{
	//1.find the earliest event in the EventList
	//2.disptchEvent.
	if(EventList.empty())
	{
		//std::cout<<"=====\nEvent List is Empty, Simulation Ends."<<std::endl;
		return;
	}
	std::vector<CEvent*>::iterator it=EventList.begin();
	std::vector<CEvent*>::iterator it2=EventList.begin();
	double t=-1000.0;
	for(;it!=EventList.end();it++)
	{
		if(t<0 ||t>(*it)->getTime())
		{
			t=(*it)->getTime();
			it2=it;
		}
	}
	CEvent *pEvt=(*it2);
	EventList.erase(it2);
	
	currentTime=pEvt->getTime();
	
	dispatchEvent(pEvt);
	
	delete pEvt;	
	
	Forward();
}


void CModel::AddElement(CElement* elm)
{
	ElementList.push_back(elm);
	elm->bindModel(this);
}

void CModel::dispatchEvent(CEvent* evt)
{
	std::vector<CElement*>::iterator it=ElementList.begin();
	for(;it!=ElementList.end();it++)
	{
		if((*it)->getType()==CElement::TYPE_MACHINE)
		{
			((CMachine*)(*it))->Respond(evt);
		}
	}
}

